package v1

import (
	"copper-cloud/models"
	"copper-cloud/pkg/app"
	"copper-cloud/pkg/e"
	"copper-cloud/pkg/logging"
	"copper-cloud/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
)

func AddFile(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}

	file, _ := c.FormFile("file")


	// Upload the file to specific dst.
	dst := "upload/" + file.Filename

	isExisted := models.FileExisted(file.Filename)
	if isExisted {
		appG.Response(http.StatusBadRequest, e.InvalidParams, traceId, nil)
		return
	}

	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
		return
	}

	f := models.File{
		FileName: file.Filename,
	}

	fileErr := models.FileInsert(f)
	logging.ZapLogger.Infow("添加文件", "名称", file.Filename)
	if fileErr != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
		return
	}

	appG.Response(http.StatusOK, e.SUCCESS, traceId, nil)

}

func MarkFile(c *gin.Context) {
	traceId := util.GetTraceID(c)
	appG := app.Gin{C: c}
	filePath := c.Query("file_path")

	filename := c.Query("file_name")
	markname := c.Query("mark_name")

	//f := models.File{
	//	FileName: filename,
	//	MarkName: markname,
	//	IsMarked: 1,
	//}

	//err := models.FileMark(f)
	//logging.ZapLogger.Infow("标记图片名称", "错误信息", err)
	//if err != nil {
	//	appG.Response(http.StatusInternalServerError, e.ERROR, traceId, nil)
	//	return
	//}

	oldFile := "upload/" + filePath + "/" + filename + ".png"
	newFile := "images/" + filePath + "/" + markname + ".png"

	_, fileErr := os.Stat(oldFile)
	if fileErr != nil {
		appG.Response(http.StatusBadRequest, e.ErrorFileNotExisted, traceId ,nil)
		return
	}

	_, pathErr := os.Stat("images/" + filePath)
	if pathErr != nil {
		_ = os.Mkdir("images/" + filePath, 777)
	}

	_ = os.Rename(oldFile, newFile)


	appG.Response(http.StatusOK, e.SUCCESS, traceId, nil)
}